// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    this.login()
  },
  login: function() {
    var that = this
    // wx.showLoading({
    //   title: '正在登录',
    //   mask: true
    // })
     wx.login({
      success(res) {
        var data = {
          code: res.code
        }
        console.log("res.code"+res.code)
        that.setCode(res.code)
        that.doLogin(data)
      }
    })
   
  },
  doLogin(data) {
    setTimeout(() => {
      console.log('自动重新登录')
    }, 1000);
    var that = this
    console.log("data",data)
    
  var url = '/wx/user/' + this.getAppId() + '/login'
    this.loginRequest(url, data,
      (res) => {
        if (res.code === 200) {
          console.log('登录成功',res.token)
          // 若登录成功，将token设置在消息头中
          that.setToken(res.token)
          if(that.tokenCallback){
            that.tokenCallback(res.token)
          }
        } else if(res.code === 500) {
          // 状态码返回 500 则绑定已有账号或自动生成账号
          // 请求授权
          wx.hideLoading()
          var openid = res.openid
          console.log('>>>>>>>>>>>>>>>>>>>>>>',openid)
          wx.showModal({
            title: '提示',
            content: '是否绑定已有账号?',
            cancelText:'注册',
            success: function (res) {
              if (res.confirm) {
                // 绑定的话去登录页面
                console.log(res)
                wx.navigateTo({
                  url: '/pages/me/login/login?openid=' + openid,
                })
              } else {
                // 请求授权创建账户并登录
                // 获取用户信息
                wx.getUserProfile({
                  desc: '用于完善用户资料',
                  success(res) {
                    console.log('授权结果', res)
                    var wxUser = {
                      nickName: res.userInfo.nickName,
                      sex: res.userInfo.gender,
                      avatar: res.userInfo.avatarUrl,
                      openid: openid,
                      appId: this.getAppId()
                    }
                    // that.setData({
                    //   ava:res.userInfo.avatarUrl
                    // })
                    that.setUserInfo(wxUser)
                    // 登录请求, 创建新用户，并绑定微信
                    this.createUser(wxUser)
                  }
                })
              }
            }
          })
        }
      }, (fail) => {
        console.log(fail)
      })
  },
  createUser(wxUser) {
    var that = this
    var url = '/wx/user/' + this.getAppId() + '/create'
    wx.showLoading({
      title: '正在登录',
    })
    this.sendPostRequest(url, wxUser, (res) => {
      wx.hideLoading()
      if (res.code == 200) {
        // 创建并登录成功
        console.log("登录成功！")
      } else {
        // 登录失败
        wx.showToast({
          title: '登录失败请重新打开小程序',
        })
      }
    })
  },
 
  globalData : {
    userInfo: null,
    protocol: "http://",
    host: "192.168.43.112",
    port: 8080,
    token: '',
    base_request:"http://localhost:8080",
    // base_request:"http://10.28.135.80:8080",
    // base_request:"https://www.runze.site/prod-api",
    // base_request: "http://82.157.176.102:8080",
    communityHospitalRegistered: false,
    communityHospitalRole: null,
    userId: null,
    userCommunityId: null,
    appId: "wxc50b63fd9357950b",
    // 判断是否第一次进入小程序
    firstEnter: true,
    idcode:'' , //用户的id code
    employ:'', // app.js的onlaunch是否加载完成
  },
  /**
  * 封装请求头
  */
  getHeader() {
    var protocol = this.globalData.protocol
    var host = this.globalData.host
    var port = this.globalData.port
    var header = protocol + host + ':' + port
    console.log('header:' + header)
    return header;
  },
  setToken(token) {
    this.globalData.token = token
  },
  getToken() {
    return this.globalData.token;
  },
  setCode(code) {
    this.globalData.idcode = code
  },
  getCode() {
    return this.globalData.idcode;
  },
  getAppId() {
    return this.globalData.appId
  },
  // 获取用户信息，需要先登录
  getUserInfo() {
    return this.globalData.userInfo
  },

  setUserInfo(userInfo) {
    this.globalData.userInfo = userInfo
  },

  sendGetRequest(url, callback, errFun) {
    var that = this
    var base_url = this.globalData.base_request
    wx.request({
      url: base_url + url,
      method:'GET',
      header:{
        'content-type': 'application/json',
        'Authorization':  this.globalData.token
      },
      success:function(res){
        // if(res.data.code == 401) {
        //   wx.switchTab({
        //     url: '/pages/index/index',
        //     success:function(e){
        //       var page = getCurrentPages().pop();
        //       if(page==undefined || page == null) return;
        //       page.onLoad();
        //     },
        //     fail: function(e) {
        //       console.log(e)
        //     }
        //   })
        // }
        callback(res.data);
      },
      fail: function(err) {
        errFun(err)
      }
    })
  },

  loginRequest(url, data, callback, errFun) {
    var that = this
    var base_url = this.globalData.base_request
    wx.request({
      url: base_url + url,
      method:'GET',
      data: data,
      header:{
        'content-type': 'application/json',
        'Authorization':  this.globalData.token
      },
      success:function(res){
        // if(res.data.code == 401) {
        //   that.regetToken()
        // }
        callback(res.data);
      },
      fail: function(err) {
        errFun(err)
      }
    })
  },
  
  sendPostRequest(url, data, callback, errFun) {
    var base_url = this.globalData.base_request
    wx.request({
      url: base_url  + url,
      method:'POST',
      data: data,
      header:{
        'content-type': 'application/json',
        'Authorization':  this.globalData.token
      },
      success:function(res){
        if(res.data.code == 401) {
          // wx.switchTab({
          //   url: '/pages/index/index',
          //   success:function(e){
          //     var page = getCurrentPages().pop();
          //     if(page==undefined || page == null) return;
          //     page.onLoad();
          //   },
          //   fail: function(e) {
          //     console.log(e)
          //   }
          // })
        }
        callback(res.data);
      },
      fail: function(err) {
        errFun(err)
      }
    })
  },
  sendGetRequestWithData(url, data, callback, errFun){
    var that = this
    var base_url = this.globalData.base_request
    wx.request({
      url: base_url + url,
      method:'GET',
      data: data,
      header:{
        'content-type': 'application/json',
        'Authorization':  this.globalData.token
      },
      success:function(res){
        if(res.data.code == 401) {
            that.login()
        }
        callback(res.data);
      },
      fail: function(err) {
        errFun(err)
      }
    })
  },
  sendPutRequest(url, data, callback, errFun) {
    var base_url = this.globalData.base_request
    wx.request({
      url: base_url  + url,
      method:'PUT',
      data: data,
      header:{
        'content-type': 'application/json',
        'Authorization':  this.globalData.token
      },
      success:function(res){
        if(res.data.code == 401) {
          // wx.switchTab({
          //   url: '/pages/index/index',
          //   success:function(e){
          //     var page = getCurrentPages().pop();
          //     if(page==undefined || page == null) return;
          //     page.onLoad();
          //   },
          //   fail: function(e) {
          //     console.log(e)
          //   }
          // })
          that.login()
        }
        callback(res.data);
      },
      fail: function(err) {
        errFun(err)
      }
    })
  },

  sendDeleteRequest(url, callback, errFun) {
    var base_url = this.globalData.base_request
    wx.request({
      url: base_url  + url,
      method:'DELETE',
      header:{
        'content-type': 'application/json',
        'Authorization':  this.globalData.token
      },
      success:function(res){
        console.log('查看删除返回值', res)
        if(res.data.code == 401) {
          that.login()
        }
        callback(res.data);
      },
      fail: function(err) {
        errFun(err)
      }
    })
  },

  regetToken(){
    console.log("调用我咯")
    var that = this
    var code = that.getCode()
    var data = {
      code: code
    }
    console.log(that.getCode())
    wx.request({
      url: that.globalData.base_request + '/wx/user/'+that.getAppId() + '/login',
      method: 'GET',
      data: data,
      header:{
        'content-type': 'application/json',
        'Authorization': this.globalData.token
      },
      success:function(res) {
        if(res.code == 200){
          console.log("保温 "+ res)
          console.log("新的token "+ res.token)
          that.setToken(res.token)
        }
      }
    })
    console.log("调用结束")
  }
})
